package com.avic.rong.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.avic.rong.R;
import com.avic.rong.bean.HomeBean;
import com.avic.rong.listener.ContentItemOnClickListener;
import com.avic.rong.listener.NoticeItemOnClickListener;
import com.avic.rong.utils.DensityUtils;
import com.avic.rong.wedgit.bannerIndicater.LoopViewPager;
import com.avic.rong.wedgit.customWedgit.MyGridView;
import com.bumptech.glide.Glide;
import com.example.minato.minastore.utils.AppUtils;
import com.example.minato.minastore.utils.GlideApp;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.ibooker.ztextviewlib.AutoVerticalScrollTextView;
import cc.ibooker.ztextviewlib.AutoVerticalScrollTextViewUtil;
import me.relex.circleindicator.CircleIndicator;


public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.MyViewHolder> {

    private static final int IS_HEADER = 2;
    private static final int IS_NORMAL = 3;
    private Context mContext;
    private LayoutInflater inflater;
    private CircleIndicator indicator;
    private LoopViewPager mLooperViewPager;
    private PicAdapter picAdapter = null;
    private RecommandAdapter recommandAdapter = null;
    private BookAdapter bookAdapter = null;
    private LibraryAdapter libraryAdapter;
    private ResouceAdapter resouceAdapter;
    private ServiceAdapter serviceAdapter;
    private ImageView advertisement;
    private HomeBean homeBean = new HomeBean();
    private CategoryAdapter categoryAdapter;//质量榜
    private AutoVerticalScrollTextView rollingTextView;
    private AutoVerticalScrollTextViewUtil aUtil;


    public MyRecycleViewAdapter(Context context) {
        this.mContext = context;
        inflater = LayoutInflater.from(context);
    }

    public void setHomeBean(HomeBean homeBean) {
        this.homeBean = homeBean;
        notifyDataSetChanged();
    }

    @Override
    public MyRecycleViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
        MyViewHolder holder;
        if (viewType == IS_HEADER) {
            View view = inflater.inflate(R.layout.fragment_home_header, parent, false);
            mLooperViewPager = (LoopViewPager) view.findViewById(R.id.viewpager);
            indicator = (CircleIndicator) view.findViewById(R.id.indicator_two);
            indicator.setViewPager(mLooperViewPager);

            ButterKnife.bind(MyRecycleViewAdapter.this,view);


            //标准分类
            RecyclerView recycler_view_category = (RecyclerView) view.findViewById(R.id.recycler_view_category);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
            linearLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
            recycler_view_category.setLayoutManager(linearLayoutManager);
            categoryAdapter = new CategoryAdapter(mContext);
            recycler_view_category.setAdapter(categoryAdapter);
            recycler_view_category.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    int leftMargin = (int) ((DensityUtils.getWindowWidth(mContext) - 5 * DensityUtils.dp2px(mContext, 46)) / 8f);
                    outRect.set(leftMargin, 0, leftMargin, 0);
                }
            });

            //通知
            rollingTextView = (AutoVerticalScrollTextView)view.findViewById(R.id.tv_advertisement);


            //热门推荐
            RecyclerView recycler_view_recommand = (RecyclerView)view.findViewById(R.id.recycler_view_recommand);
            recommandAdapter = new RecommandAdapter(mContext);
            LinearLayoutManager recommandayoutManager = new LinearLayoutManager(mContext);
            recommandayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
            recycler_view_recommand.setLayoutManager(recommandayoutManager);
            recycler_view_recommand.addItemDecoration(new SpaceItemDecoration(0,10));
            recycler_view_recommand.setAdapter(recommandAdapter);

            //广告
            advertisement = (ImageView)view.findViewById(R.id.advertisement);


            //标准资源
            MyGridView grid_view_resource = (MyGridView)view.findViewById(R.id.grid_view_resource);
            resouceAdapter = new ResouceAdapter(mContext);
            grid_view_resource.setAdapter(resouceAdapter);
            grid_view_resource.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    if (position == 0){
//                        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList?keyword=GJB"));
//                    }else if(position == 1){
//                        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList?keyword=HB"));
//                    }else if(position == 2){
//                        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList?keyword=GB"));
//                    }else if(position == 3){
//                        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList?catId=1988"));
//                    }
                }
            });


            //专题库
            RecyclerView recycler_view_library = (RecyclerView)view.findViewById(R.id.recycler_view_library);
            libraryAdapter = new LibraryAdapter(mContext);
            LinearLayoutManager libraryLayoutManager = new LinearLayoutManager(mContext);
            libraryLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
            recycler_view_library.addItemDecoration(new SpaceItemDecoration(0,15));
            recycler_view_library.setLayoutManager(libraryLayoutManager);
            recycler_view_library.setAdapter(libraryAdapter);


            //知识服务
            MyGridView grid_view_service = (MyGridView)view.findViewById(R.id.grid_view_service);
            serviceAdapter = new ServiceAdapter(mContext);
            grid_view_service.setAdapter(serviceAdapter);
            grid_view_service.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 0){
//                        mContext.startActivity(KnowlegeServiceActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/content/newsCenter/detail/1485" +".html"));
                    }else if(position == 1){
//                        mContext.startActivity(KnowlegeServiceActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/content/newsCenter/detail/1111" +".html"));
                    }else if(position == 2){
//                        mContext.startActivity(KnowlegeServiceActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/content/newsCenter/detail/1110" +".html"));
                    }else if(position == 3){
//                        mContext.startActivity(KnowlegeServiceActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/content/newsCenter/detail/1112" +".html"));
                    }
                }
            });


            //图书
            RecyclerView recycler_view_book = (RecyclerView)view.findViewById(R.id.recycler_view_book);
            bookAdapter = new BookAdapter(mContext);
            LinearLayoutManager bookLayoutManager = new LinearLayoutManager(mContext);
            bookLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
            recycler_view_book.addItemDecoration(new SpaceItemDecoration(0,15));
            recycler_view_book.setLayoutManager(bookLayoutManager);
            recycler_view_book.setAdapter(bookAdapter);


            holder = new MyViewHolder(view, viewType);
        } else{
            View view = inflater.inflate(R.layout.fragment_home_recyclerview, parent, false);
            holder = new MyViewHolder(view, viewType);
        }


        return holder;
    }


    @Override
    public void onBindViewHolder(MyRecycleViewAdapter.MyViewHolder holder, int position) {
        if (position == 0 && holder.viewType == IS_HEADER) {


            if (categoryAdapter != null) {
//                categoryAdapter.setmData(homeResourceBean.getCategory().getList());
            }

            ArrayList noticeList = new ArrayList<>();
            for(HomeBean.CriterionBean tmp : homeBean.getNoticeList()){
                noticeList.add(tmp.getTargetName());
            }

            // 初始化
            aUtil = new AutoVerticalScrollTextViewUtil(rollingTextView, noticeList);
            aUtil.setDuration(5000)// 设置上下滚动事件间隔
                    .start();
            aUtil.setOnMyClickListener(new NoticeItemOnClickListener(aUtil,mContext,homeBean.getNoticeList()));


            //热门推荐
            recommandAdapter.setData(homeBean.getRecommendList());

            //广告
            if (homeBean.getAdList().size() > 0){
                Glide.with(mContext).load(homeBean.getAdList().get(0).getContent()).into(advertisement);
                advertisement.setOnClickListener(new ContentItemOnClickListener(mContext,homeBean.getAdList().get(0).getUrl()));
            }

            //标准资源
            resouceAdapter.setData(new ArrayList<String>());

            //专题库
            libraryAdapter.setData(homeBean.getBZztList());

            //知识服务
            serviceAdapter.setData(new ArrayList<String>());

            //图书
            bookAdapter.setData(homeBean.getBZrxtsList());

            if (homeBean.getAdvertismentList().size() > 0) {//轮播图处理

                if (mLooperViewPager.getChildCount() > 0) mLooperViewPager.removeAllViews();
                if (picAdapter == null) {//只有第一次进来的时候加载banner
                    picAdapter = new PicAdapter(mContext, homeBean.getAdvertismentList());
                    mLooperViewPager.setAdapter(picAdapter);
                    mLooperViewPager.setLooperPic(true);
                    mLooperViewPager.setOffscreenPageLimit(mLooperViewPager.getChildCount() / 2);
                    indicator.setViewPager(mLooperViewPager);
                }
            }

            //处理banner上下滑动事件冲突
//            dealRecyclerViewEventConfilt(mLooperViewPager);

        } else if (holder.viewType == IS_NORMAL) {


//            ContentItemBean topNewsBean = topNewsBeanList.get(position - 1);
            holder.textView.setText(homeBean.getLastrmbzList().get(position - 1).getTargetName());
            holder.tv_say_date.setText(homeBean.getLastrmbzList().get(position - 1).getPublicTime());
            GlideApp.with(mContext).load(homeBean.getLastrmbzList().get(position - 1).getTargetImg())
                    .placeholder(R.mipmap.empty).into(holder.img_say_pic);

            holder.itemView.setOnClickListener(new ContentItemOnClickListener(mContext, AppUtils.BASE_URL + "app/biaozhun/dynamicDetail/" + homeBean.getLastrmbzList().get(position - 1).getTargetId()));

        } else {
//            holder.btn_top_more.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onUpTimeClick(View view) {
//                    mContext.startActivity(ZiXunActivity.getIntent(mContext));
//                }
//            });
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return IS_HEADER;
        } else {
            return IS_NORMAL;
        }
    }

    @Override
    public int getItemCount() {
        if (homeBean.getLastrmbzList().size() == 0) {
            return 1;
        } else {
            return homeBean.getLastrmbzList().size() + 1;
        }
    }


    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textView;
        int viewType;
        TextView tv_say_date;
        TextView tv_say_source;
        ImageView img_say_pic;

        public MyViewHolder(View itemView, int type) {
            super(itemView);
            this.viewType = type;
            if (viewType == IS_HEADER) {
//                textView = (TextView)itemView.findViewById(R.id.wang);
            } else {
                textView = (TextView) itemView.findViewById(R.id.tv_say_title);
                tv_say_date = (TextView) itemView.findViewById(R.id.tv_say_date);
                tv_say_source = (TextView) itemView.findViewById(R.id.tv_say_source);
                img_say_pic = (ImageView) itemView.findViewById(R.id.img_say_pic);
            }

        }
    }


    /**
     * 通知
     */
    @OnClick(R.id.tv_notice_more)
    public void clickAdvMore(){
//        mContext.startActivity(NoticeListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/notice"));
    }

    /**
     * 热门推荐
     */
    @OnClick(R.id.tv_hot_criterion_more)
    public void clickHotCriterionMore(){
//        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList"));
    }


    /**
     * 标准资源
     */
    @OnClick(R.id.tv_criterion_more)
    public void clickCriterionMore(){
//        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/criterionList"));
    }


    /**
     * 专题库
     */
    @OnClick(R.id.tv_library_more)
    public void clickLibraryMore(){
//        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/topicLibrary"));
    }


    /**
     * 知识服务更多
     */
    @OnClick(R.id.tv_service_more)
    public void clickServiceMore(){
//        mContext.startActivity(ServiceListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/knowserviceList"));
    }


    /**
     * 图书更多
     */
    @OnClick(R.id.tv_book_more)
    public void clickBookMore(){
//        mContext.startActivity(CriterionListActivity.queryIntent(mContext, AppUtils.BASE_URL + "app/biaozhun/bookList"));
    }

    /**
     * 动态信息
     */
    @OnClick(R.id.tv_dynamic)
    public void clickDanymic(){
//        mContext.startActivity(DynamicListActivity.queryIntent(mContext, AppUtils.BASE_URL + "/app/biaozhun/dynamic"));
    }


    public void stopVerticalTextView(){
        if (aUtil != null){
            aUtil.stop();
        }
    }


    public void dealRecyclerViewEventConfilt(final LoopViewPager mLooperViewPager) {

        mLooperViewPager.setOnTouchListener(new View.OnTouchListener() {
            int lastX = 0;
            int lastY = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int x = (int) motionEvent.getRawX();
                int y = (int) motionEvent.getRawY();

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = x;
                        lastY = y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int deltaY = y - lastY;
                        int deltaX = x - lastX;
                        if (Math.abs(deltaX) < Math.abs(deltaY)) {
                            mLooperViewPager.getParent().getParent().requestDisallowInterceptTouchEvent(false);
                        } else {
                            mLooperViewPager.getParent().getParent().requestDisallowInterceptTouchEvent(true);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }
}
